import re
from datetime import timedelta
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.models.user import User
from app import db

auth_bp = Blueprint('auth', __name__)

def validate_phone(phone):
    """验证手机号格式"""
    pattern = r'^1[3-9]\d{9}$'
    return re.match(pattern, phone) is not None

def validate_password(password):
    """验证密码强度"""
    if len(password) < 6:
        return False, "密码长度至少6位"
    if len(password) > 20:
        return False, "密码长度不能超过20位"
    return True, ""

@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json() or {}
        phone = data.get('phone', '').strip()
        password = data.get('password', '')
        
        # 验证必填字段
        if not phone:
            return jsonify({'error': '手机号不能为空'}), 400
        if not password:
            return jsonify({'error': '密码不能为空'}), 400
        
        # 验证手机号格式
        if not validate_phone(phone):
            return jsonify({'error': '手机号格式不正确'}), 400
        
        # 验证密码强度
        is_valid, error_msg = validate_password(password)
        if not is_valid:
            return jsonify({'error': error_msg}), 400
        
        # 检查手机号是否已存在
        if User.query.filter_by(phone=phone).first():
            return jsonify({'error': '该手机号已注册'}), 400
        
        # 创建新用户
        user = User(phone=phone)
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        # 生成 JWT token
        access_token = create_access_token(
            identity=str(user.id),
            expires_delta=timedelta(days=7)
        )
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'access_token': access_token,
            'user': user.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'注册失败: {str(e)}'}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json() or {}
        phone = data.get('phone', '').strip()
        password = data.get('password', '')
        
        # 验证必填字段
        if not phone:
            return jsonify({'error': '手机号不能为空'}), 400
        if not password:
            return jsonify({'error': '密码不能为空'}), 400
        
        # 查找用户
        user = User.query.filter_by(phone=phone).first()
        if not user:
            return jsonify({'error': '手机号或密码错误'}), 401
        
        # 验证密码
        if not user.check_password(password):
            return jsonify({'error': '手机号或密码错误'}), 401
        
        # 生成 JWT token
        access_token = create_access_token(
            identity=str(user.id),
            expires_delta=timedelta(days=7)
        )
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'access_token': access_token,
            'user': user.to_dict()
        })
        
    except Exception as e:
        return jsonify({'error': f'登录失败: {str(e)}'}), 500

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取用户信息"""
    try:
        user_id = get_jwt_identity()
        user = User.query.get(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        return jsonify({
            'success': True,
            'user': user.to_dict()
        })
        
    except Exception as e:
        return jsonify({'error': f'获取用户信息失败: {str(e)}'}), 500

@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户登出"""
    # JWT 是无状态的，登出主要是前端删除 token
    return jsonify({
        'success': True,
        'message': '登出成功'
    })
